﻿/**
 * @ngdoc module
 * @name assignment.services
 * @description
 *   任务指派模块服务
 */

angular.module('assignment.services', [])


/**
 * @ngdoc service
 * @name Assignment
 * @module assignment.services
 * @description
 *   任务指派通用服务
 */

.factory('Assignment', function($rootScope, $http, $state, $filter, $ionicLoading, Settings, Utils, User) {
  var getModuleUrl = function () {
    return Settings.rootUrl + '/assignment';
  }

  var DATETIME_FORMAT = 'yyyy-MM-dd HH:mm';

  // 状态对应 0 未读，1 进行中，2 已完成，3 已评价，4 已取消
  var operation = {
    // 指派人可用操作
    designee: {
      '0': ['edit', 'remove', 'urge', 'cancel', 'delay', 'remind'],
      '1': ['edit', 'remove', 'done', 'cancel', 'delay', 'remind'],
      '2': ['edit', 'remove', 'stamp', 'restart'],
      '3': ['edit', 'remove', 'restart'],
      '4': ['edit', 'remove', 'restart']
    },
    // 负责人可用操作
    charge: {
      '0': ['done', 'remind'],
      '1': ['done', 'applyDelay', 'applyCancel', 'remind'],
      '2': ['restart'],
      '3': ['restart'],
      '4': ['restart']
    }
    // 参与人从头到尾都只能评论，就是个打酱油的
  };

  return {
    getRole: function(task) {
      if(User.uid == task.designeeuid) {
        return 'designee';
      } else if(User.uid == task.chargeuid) {
        return 'charge';
      } else if(task.participantuid.split(',').indexOf(User.uid) !== -1) {
        return 'participant';
      }
      return '';
    },

    getRoleText: function(task) {
      var text = {
        'charge': '负责人',
        'designee': '指派人',
        'participant': '参与人'
      };
      return text[this.getRole(task)] || '';
    },

    getStampPath: function(value, stamps) {
      var path = '';
      
      angular.forEach(stamps, function(stamp) {
        if(value == stamp.value) {
          path = stamp.stampPath;
        }
        return false;
      });

      return path;
    },

    /**
     * @ngdoc method
     * @name Assignment#getEnableOperation
     * @description 
     *    获取某条任务数据允许的操作
     * @param {Object} task
     * @returns {Array} 允许操作数组
     */
    getEnableOperation: function(task) {
      var op = User.uid == task.designeeuid ? 
      operation.designee:
      User.uid == task.chargeuid ?
      operation.charge:
      {};

      return op[task.status] || [];
    },

    /**
     * @ngdoc method
     * @name Assignment#convertDateTime
     * @description 
     *   将日期转为字符串
     *   根据表单控件支持情况，当支持datetime-local时，格式为 yyyy-MM-ddThh:ii
     *   否则格式为 yyyy-MM-dd hh:ii
     * @param {Date} date 日期
     * @returns {String}  时间字符串
     */
    convertDateTime: function(date) {
      date = angular.isDate(date) ? date : new Date(date);

      if(Utils.isDateTimeLocalSupport) {
        date = new Date(+date - (date.getTimezoneOffset() * 60000));
        return date.toJSON().slice(0, 16);
      } else {
        return $filter('date')(date, DATETIME_FORMAT);
      }
    },

    formatDatetime: function(date) {
      return $filter('date')(date, DATETIME_FORMAT);
    },

    /**
     * @ngdoc method
     * @name Assignment#correctDateTime
     * @description 
     *   将 datetime-local 的值转为需要的格式
     * @param {String} dateStr
     * @returns {String}
     */
    correctDateTime: function(dateStr) {
      var date = new Date(dateStr);

      if(Utils.isDateTimeLocalSupport) {
        date = new Date(+date + (date.getTimezoneOffset() * 60000));
      }

      return this.formatDatetime(date);
    },

    /**
     * @ngdoc method
     * @name Assignment#correctFormData
     * @description 
     *   校正将要提交的数据
     * @param {Object} form 表单数据
     * @returns {Object}    校正后的表单数据
     */
    correctFormData: function(form) {
      form = angular.extend({}, form);

      form.chargeuid = User.addPrefix(form.chargeuid);
      form.participantuid = User.addPrefix(form.participantuid) || '';

      // form.starttime = this.correctDateTime(form.starttime) || '';
      // form.endtime = this.correctDateTime(form.endtime);
      form.starttime = this.formatDatetime(form.starttime);
      form.endtime = this.formatDatetime(form.endtime);

      form.description = form.description || '';
      // 目前手机端没做附件，但由于后端有检验这一参数，所以加上
      form.attachmentid = '';

      return form;
    },

    /**
     * @ngdoc method
     * @name Assignment#get
     * @description 
     *    获取某一条任务
     * @param {Object}   params     参数，正常情况下只需要任务 id
     * @returns {Object} promise
     */
    get: function(params) {
      return $http.get(getModuleUrl() + '/edit', {
        params: params
      })
    },

    /**
     * @ngdoc method
     * @name Assignment#get
     * @description 
     *    获取某一条任务及任务相关的数据
     * @param {Object}   params     参数，正常情况下只需要任务 id
     * @returns {Object} promise
     */
    getFullInfo: function(params) {
      params = params || {};
      params.assignmentId = params.id;
      return $http.get(getModuleUrl() + '/show', {
        params: params
      })
    },

    /**
     * @ngdoc method
     * @name Assignment#create
     * @description 
     *    创建一条新的任务
     * @param {Object} data
     * @returns {Object} promise
     */
    create: function(data) {
      data.formhash = User.formhash
      return $http.post(getModuleUrl() + '/add&addsubmit=1', data)
      .success(function(res) {
        $rootScope.$broadcast('assignment.create', data, res);
      });
    },

    /**
     * @ngdoc method
     * @name Assignment#update
     * @description 
     *   修改某一条任务
     * @param {String}     id     该任务 id
     * @param {Object}     data   任务新数据
     * @returns {Object}   promise
     */
    update: function(id, data) {
      return $http.post(getModuleUrl() + '/edit&id=' + id, data)
      .success(function(res) {
        $rootScope.$broadcast('assignment.update', id, data, res);
      });
    },

    /**
     * @ngdoc method
     * @name Assignment#remove
     * @description 
     *   删除任务
     * @param {Object}   params   参数
     *   params.id  {String} 任务id，必须项
     * @returns {Object} promise
     */
    remove: function(params) {
      return $http.post(getModuleUrl() + '/del', params)
    },

    /**
     * @ngdoc method
     * @name Assignment#getSubordinates
     * @description 
     *   获取指定用户的下属数据
     * @param {Object}   params   参数
     *   params.uid            {String} 用户id
     * @returns {Object} promise
     */
    getSubordinates: function(params) {
      return $http.get(Settings.rootUrl + '/assignmentunfinished/subList&op=getsubordinates', {
        params: params
      })
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name Assignment#getSubordinates
     * @description 
     *   评价任务
     * @param {Object}   params   参数
     *   params.id            {String} 任务id
     *   params.stamp         {String} 图章值
     * @returns {Object} promise
     */
    stamp: function(params) {
      return $http.post(Settings.rootUrl + '/assignmentunfinished/ajaxEntrance&op=stamp', params)
      .error(Settings.requestError);
    }
  };
})

/**
 * @ngdoc service
 * @name AssignmentUnfinished
 * @module assignment.services
 * @description
 *   任务指派未完成列表数据
 */
.factory('AssignmentUnfinished', function($rootScope, $http, Settings, IbPopup) {
  var getModuleUrl = function () {
    return Settings.rootUrl + '/assignmentunfinished';
  }

  function serverError(res) {
    if(!res.isSuccess) {
      IbPopup.tip(res.msg);
    }
  }

  var ret = {
    /**
     * @ngdoc method
     * @name AssignmentUnfinished#get
     * @description 
     *   获取未完成列表数据
     * @returns {Object} promise
     */
    get: function() {
      return $http.get(getModuleUrl()).error(Settings.requestError);
    },

    getSubList: function(params) {
      return $http.get(getModuleUrl() + '/subList', {
        params: params
      })
      .error(Settings.requestError);
    },
    /**
     * @ngdoc method
     * @name AssignmentUnfinished#urge
     * @description 
     *   催办任务
     * @param {Object}   params   参数
     *   params.id  {String} 任务id，必须项
     * @returns {Object} promise
     */
    urge: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=push', params)
      .success(serverError)
      .success(function(res) {
        $rootScope.$broadcast('assignment.urge', params, res);
      })
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#done
     * @description 
     *   完成任务
     * @param {Object}   params   参数
     *   params.id  {String} 任务id，必须项
     * @returns {Object} promise
     */
    done: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=toFinished', params)
      .success(serverError)
      .success(function(res) {
        $rootScope.$broadcast('assignment.done', params, res);
      })
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#restart
     * @description 
     *   重启任务
     * @param {Object}   params   参数
     *   params.id  {String} 任务id，必须项
     * @returns {Object} promise
     */
    restart: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=restart', params)
      .success(serverError)
      .success(function(res) {
        $rootScope.$broadcast('assignment.restart', params, res);
      })
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#applyDelay
     * @description 
     *   申请任务延迟
     * @param {Object}     params   参数
     *   params.id            {String} 任务id，必须项
     *   params.starttime     {String} 开始时间，格式为 yyyy-MM-dd HH:mm
     *   params.endtime       {String} 结束时间，格式同上
     *   params.delayReason   {String} 延迟原因
     * @returns {Object} promise
     */
    applyDelay: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=applyDelay', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#applyCancel
     * @description 
     *   申请任务取消
     * @param {Object}     params   参数
     *   params.id            {String} 任务id，必须项
     *   params.cancelReason  {String} 取消原因
     * @returns {Object} promise
     */
    applyCancel: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=applyCancel', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#dealDelayApply
     * @description 
     *   延期申请处理
     * @param {Object}   params   参数
     *   params.id       {String} 任务id，必须项
     *   params.agree    {Number} 是否同意，0 表拒绝，1表同意
     * @returns {Object} promise
     */
    dealDelayApply: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=runApplyDelayResult', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#dealCancelApply
     * @description 
     *   延期取消处理
     * @param {Object}   params   参数
     *   params.id       {String} 任务id，必须项
     *   params.agree    {Number} 是否同意，0 表拒绝，1表同意
     * @returns {Object} promise
     */
    dealCancelApply: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=runApplyCancelResult', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#delay
     * @description 
     *   延期任务
     * @param {Object}   params   参数
     *   params.id       {String} 任务id，必须项
     * @returns {Object} promise
     */
    delay: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=delay', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#cancel
     * @description 
     *   取消任务
     * @param {Object}   params   参数
     *   params.id       {String} 任务id，必须项
     * @returns {Object} promise
     */
    cancel: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=cancel', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    /**
     * @ngdoc method
     * @name AssignmentUnfinished#remind
     * @description 
     *   设置提醒
     * @param {Object}   params   参数
     *   params.id            {String} 任务id，必须项
     *   params.remindTime    {String} 提醒时间
     *   params.remindContent {String} 提醒内容
     * @returns {Object} promise
     */
    remind: function(params) {
      return $http.post(getModuleUrl() + '/ajaxEntrance&op=remind&remindsubmit=1', params)
      .success(serverError)
      .error(Settings.requestError);
    },

    getRemindData: function(params) {
      return $http.get(getModuleUrl() + '/ajaxEntrance&op=remind', { params: params })
      .success(serverError)
      .error(Settings.requestError);
    }
  };

  return ret;
})

/**
 * @ngdoc service
 * @name AssignmentFinished
 * @module assignment.services
 * @description
 *   任务指派已完成列表数据
 */
.factory('AssignmentFinished', function($rootScope, Settings, IbList) {
  var assignmentFinished = new IbList('/assignmentfinished', {
    idAttr: 'assignmentid'
  });
  // 已完成列表搜索功能后端参数与其他模块不一样
  // 需要重写 search 方法
  // 后端泥垢了 (╯°Д°)╯︵ ┻━┻
  assignmentFinished.search = function(keyword) {
    if(keyword.trim() === '') {
      return this.fetch({
        offset: 0,
      }, true);
    } else {
      return this.fetch({
        offset: 0,
        param: 'search',
        keyword: keyword
      }, true);
    }

  };

  return assignmentFinished;
})


/**
 * @ngdoc filter
 * @name assignment.services.filter:asmStatusText
 * @function
 * @description
 *  将任务状态标识转化为文本
 *  
 * @param   {string}  status  任务状态标识
 * @returns {string}  任务状态文本
 */
.filter('asmStatusText', function() {
  var statusMap = {
    0: '未读',
    1: '进行中',
    2: '已完成',
    3: '已评价',
    4: '已取消'
  };

  return function(status) {
    return statusMap[+status] || '';
  };
})